package cn.tsvtc.shop.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.tsvtc.shop.constant.RedisConstant;
import cn.tsvtc.shop.entity.CartItemVO;
import cn.tsvtc.shop.entity.LoginUser;
import cn.tsvtc.shop.entity.ResultMessage;
import cn.tsvtc.shop.pojo.Order;
import cn.tsvtc.shop.service.OrderService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author: Athena
 * @date: 2020/11/6 15:30
 * @description:
 */
@Slf4j
@Controller
@RequestMapping("order")
public class OrderController {

    private RedisTemplate redisTemplate;

    private OrderService orderService;

    private RestTemplate restTemplate;

    @Autowired
    public OrderController(RestTemplate restTemplate,OrderService orderService,RedisTemplate redisTemplate){
        this.restTemplate=restTemplate;
        this.orderService=orderService;
        this.redisTemplate=redisTemplate;
    }

    /**
     * 进入订单显示页面
     * @param model
     * @param orderId
     * @return
     */
    @RequestMapping("orderPage")
    public String orderPage(Model model,String orderId){
        //订单选择页面从前端获取临时orderid,model加入订单总价以及选中的购物车内容
        try {
            //将order存入redis临时存储
            log.error("orderPage 从前端拿到的是 "+orderId);
            Order order = (Order) redisTemplate.opsForValue().get(RedisConstant.ORDER + orderId);

            //将临时的选中的购物车存入redis
            List<CartItemVO> cartItemVOList= (List<CartItemVO>) redisTemplate.opsForValue().get(RedisConstant.ORDER_CART+orderId);


            model.addAttribute("order",order);
            model.addAttribute("carts",cartItemVOList);
            return "createorder.html";
        } catch (Exception e) {
            e.printStackTrace();
            return "createorder.html";
        }


    }

    /**
     * 订单显示页面提交，准备返回支付宝页面
     * @param model
     * @param uuid
     * @param orderId
     * @return
     */
    @RequestMapping("orderPageByCart")
    @ResponseBody
    public String orderPageByCart(Model model,@CookieValue(name = "login_token",required = false) String uuid,String orderId){
        //获取前端传过来的临时order id，从redis读取有效时间内的order
        //如果有，就将生成的订单存到数据库持久化并返回支付页面

        //后端持久化订单并返回支付宝页面链接，前端访问
//        String url="http://shop-user-service:8001/login/status.action";
//        String url2="http://shop-cart-service:8005/cart/show";
//        HttpHeaders headers=new HttpHeaders();
//        List cookie=new ArrayList();
//        cookie.add("login_token=" + uuid);
//        headers.put(HttpHeaders.COOKIE,cookie);
//        HttpEntity httpEntity=new HttpEntity(headers);
//        ResultMessage resultMessage = restTemplate.postForObject(url,httpEntity, ResultMessage.class);
//
//        ResultMessage resultMessage1 = restTemplate.postForObject(url2,httpEntity, ResultMessage.class);
//
//        if(resultMessage.getState()&&resultMessage1.getState()){
//            Object data = resultMessage.getData();
//            Object data1 = resultMessage1.getData();
//            try {
//                //String loginUserJson= (String) data;
//                //String cartItemVOListJson= (String) data1;
//                //LoginUser loginUser= JSON.parseObject(loginUserJson,LoginUser.class);
//                LoginUser loginUser= BeanUtil.toBean(data,LoginUser.class);
//                //List<CartItemVO> cartItemVOList= JSON.parseObject(cartItemVOListJson,List.class);
//                List<CartItemVO> cartItemVOList= new ArrayList<>();
//                ArrayList<LinkedHashMap> temp= (ArrayList) data1;
//                for (LinkedHashMap linkedHashMap : temp) {
//                    CartItemVO cartItemVO = BeanUtil.toBean(linkedHashMap, CartItemVO.class);
//                    cartItemVOList.add(cartItemVO);
//                }
//
//
//                Order order = orderService.addOrder(cartItemVOList, loginUser.getId());
//                model.addAttribute("order",order);
//                return "pay.html";
//
//
//            } catch (Exception e) {
//                e.printStackTrace();
//                model.addAttribute("order",data1);
//                return "pay.html";
//            }
//        }else{
//            return "";
//        }
        return null;

    }


    /**
     * 购物车页面前端ajax提交
     * @param model
     * @param uuid
     * @param checked
     * @return
     */
    @PostMapping("makeOrder")
    @ResponseBody
    public ResultMessage makeOrder(Model model,@CookieValue(name = "login_token",required = false) String uuid,
                                   @RequestBody List<Integer> checked){
        //在购物车通过ajax访问这个接口，cookie传过来用户id以及json的数组包含选择的购物车内容



        String url="http://shop-user-service:8001/login/status.action";
        String url2="http://shop-cart-service:8005/cart/show";
        HttpHeaders headers=new HttpHeaders();
        List cookie=new ArrayList();
        cookie.add("login_token=" + uuid);
        headers.put(HttpHeaders.COOKIE,cookie);
        HttpEntity httpEntity=new HttpEntity(headers);
        ResultMessage resultMessage = restTemplate.postForObject(url,httpEntity, ResultMessage.class);

        ResultMessage resultMessage1 = restTemplate.postForObject(url2,httpEntity, ResultMessage.class);

        if(resultMessage.getState()&&resultMessage1.getState()){
            Object data = resultMessage.getData();
            Object data1 = resultMessage1.getData();
            try {
                //String loginUserJson= (String) data;
                //String cartItemVOListJson= (String) data1;
                //LoginUser loginUser= JSON.parseObject(loginUserJson,LoginUser.class);
                LoginUser loginUser= BeanUtil.toBean(data,LoginUser.class);
                //List<CartItemVO> cartItemVOList= JSON.parseObject(cartItemVOListJson,List.class);
                List<CartItemVO> cartItemVOList= new ArrayList<>();
                ArrayList<LinkedHashMap> temp= (ArrayList) data1;
                for (int i = 0; i < temp.size(); i++) {
                    LinkedHashMap linkedHashMap = temp.get(i);
                    CartItemVO cartItemVO = BeanUtil.toBean(linkedHashMap, CartItemVO.class);
                    if(checked.contains(i)){
                        //前台传过来的数组里包含这个购物车元素，即是选中要结算的商品
                        cartItemVOList.add(cartItemVO);
                    }
                }



                Order order = orderService.addOrder(cartItemVOList, loginUser.getId());
                //将order存入redis临时存储
                redisTemplate.opsForValue().set(RedisConstant.ORDER+order.getId(),order);
                log.error("redis存入了  "+RedisConstant.ORDER+order.getId()+order);

                //将临时的选中的购物车存入redis
                redisTemplate.opsForValue().set(RedisConstant.ORDER_CART+order.getId(),cartItemVOList);
                //model.addAttribute("order",order);
                log.error("redis存入了  "+RedisConstant.ORDER_CART+order.getId());
                log.error("返回给前端的是  "+order.getId());

                return new ResultMessage(true,"success",order.getId());



            } catch (Exception e) {
                e.printStackTrace();
                return new ResultMessage(false,"failed","");
            }
        }else{
            return new ResultMessage(false,"failed","");
        }
    }

//    @PostMapping("addOrder")
//    public ResultMessage addOrder(Model model, @CookieValue(name = "login_token",required = false) String uuid,
//                                  @RequestBody JSONObject param){
//        String url="http://shop-user-service:8001/login/status.action";
//        HttpHeaders headers=new HttpHeaders();
//        List cookie=new ArrayList();
//        cookie.add("login_token=" + uuid);
//        headers.put(HttpHeaders.COOKIE,cookie);
//        HttpEntity httpEntity=new HttpEntity(headers);
//        ResultMessage resultMessage = restTemplate.postForObject(url,httpEntity, ResultMessage.class);
//        Object data = resultMessage.getData();
//        if (data!=null){
//            LoginUser loginUser= (LoginUser) data;
//            //Order order = orderService.addOrder(map, loginUser.getId());
//            //model.addAttribute("order",order);
//            //return new ResultMessage(true,"success",order.getId());
//            Set<String> strings = param.keySet();
//            for (String string : strings) {
//                Object o = param.get(string);
//                log.error("=======================>"+o);
//            }
//
//            return new ResultMessage(false,"failed",null);
//        }else{
//            return new ResultMessage(false,"failed",null);
//        }
//    }

}
